package com.lej.dataservice.club.http.bean

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData

sealed class ResStatus<out T> {
    data class Loading(val d: String = "") : ResStatus<Nothing>()
    data class Success<out T>(val data: T) : ResStatus<T>()
    data class Error(val error: Throwable) : ResStatus<Nothing>()

    fun getDataOrNull(): T? = if (this is Success) data else null
}

inline fun <T> MutableLiveData<ResStatus<T>>.data(crossinline block: (T) -> Unit) {
    (value as? ResStatus.Success)?.let { block(it.data) }
}

inline fun <T> MutableLiveData<ResStatus<T>>.onSuccess(
    owner: LifecycleOwner,
    crossinline block: (T) -> Unit
) : MutableLiveData<ResStatus<T>> {
    observe(owner) { if (it is ResStatus.Success) block(it.data) }
    return this
}

inline fun <T> MutableLiveData<ResStatus<T>>.onLoading(
    owner: LifecycleOwner,
    crossinline block: () -> Unit
) : MutableLiveData<ResStatus<T>> {
    observe(owner) { if (it is ResStatus.Loading) block() }
    return this
}

inline fun <T> MutableLiveData<ResStatus<T>>.onError(
    owner: LifecycleOwner,
    crossinline block: (Throwable) -> Unit
) : MutableLiveData<ResStatus<T>> {
    observe(owner) { if (it is ResStatus.Error) block(it.error) }
    return this
}
